package com.wstuo.common.config.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wstuo.common.config.onlinelog.dto.UserOnlineLogQueryDTO;
import com.wstuo.common.config.onlinelog.service.IUserOnlineLogService;
import com.wstuo.common.dto.PageDTO;

public class UpdateUserOfflineLog implements Filter{
	public WebApplicationContext ctx = null;
	public ServletContext application = null;
	@SuppressWarnings("unchecked")
	public void destroy() {
		//服务器重启时更新用户的下线时间
		IUserOnlineLogService userservice = (IUserOnlineLogService) ctx
				.getBean("useronlinelogService");
		UserOnlineLogQueryDTO useronlinelogQueryDTO = new UserOnlineLogQueryDTO();
		useronlinelogQueryDTO.setIsSearchOffLine(true);
		PageDTO dtos = userservice.findUserOnlineByPager(useronlinelogQueryDTO , 0, 10000);
		userservice.updateOnline(dtos.getData());
		//服务器重启时清除所有session
		Map<String, HttpSession> sessionMap = (Map<String, HttpSession>) application.getAttribute("sessionMap");
		if(sessionMap!=null && sessionMap.values()!=null){
			HttpSession[] sessions = new HttpSession[sessionMap.size()];
			int count = 0;
			for(HttpSession session : sessionMap.values()){
				sessions[count++] = session;
			}
			for(int i = 0 ; i < sessionMap.size() ; i++){
				sessions[i].invalidate();
			}
		}
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		chain.doFilter(req, res);
	}

	public void init(FilterConfig conf) throws ServletException {
		ctx = WebApplicationContextUtils
				.getWebApplicationContext(conf.getServletContext());
		application = conf.getServletContext();
	}

}
